package com.io;


import java.io.*;

class FileOutputInputStreamUtils {


    /**
     * @param srcFile    源文件
     * @param targetFile 目标路径
     * @throws IOException
     */
    public static void copyFile(File srcFile, File targetFile) throws IOException {
        BufferedInputStream bin = null;
        BufferedOutputStream bout = null;
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            bin = new BufferedInputStream(new FileInputStream(srcFile));
            bout = new BufferedOutputStream(new FileOutputStream(new File(targetFile, srcFile.getName())));
            byte[] buff = new byte[1024];
            int len = -1;

            while ((len = bin.read(buff)) > 0) {
                bout.write(buff, 0, len);
                bout.flush();
            }
            System.out.println("拷贝" + srcFile + "到" + targetFile);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            bin.close();
            bout.close();
        }

    }


    /**
     * 拷贝一个目录
     *
     * @param srcFile
     * @param targetFile
     * @throws IOException
     */
    public static void copyDir(File srcFile, File targetFile) throws IOException {
        if (!srcFile.exists()) {
            System.out.println("拷贝文件路径不正确");
            return;
        }

        if (srcFile.isFile()) {
            copyFile(srcFile, targetFile);
            return;
        }

        //src是目录
        targetFile = new File(targetFile, srcFile.getName());
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        File[] files = srcFile.listFiles();
        if (files == null) {
            return;
        }
        for (File file : files) {
            copyDir(file, targetFile);
        }
    }
}


public class BufferedInputOutputStreamDemo01 {

    public static void main(String[] args) throws IOException {
//        FileOutputInputStreamUtils.copyFile(
//                new File("D:\\dev\\java-intelli-j\\corejava\\corejava_io\\src\\day01\\BufferInputStreamDemo01.java"),
//                new File("D:\\dev\\1\\BufferInputStreamDemo01.java"));
        FileOutputInputStreamUtils.copyDir(
                new File("D:\\dev\\java-intelli-j\\corejava\\corejava_io\\src\\day01"),
                new File("D:\\dev\\1"));


    }


}
